package com.ly.demo.utils;

import cn.hutool.core.util.XmlUtil;
import com.ly.demo.entity.ReceiveMessage;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @author liuyang
 */
public class WeixinMsgUtil {

    // 事件-关注
    private static String EVENT_SUBSCRIBE = "subscribe";

    /**
     * 微信消息转对象
     *
     * @param xml
     * @return
     */
    public static ReceiveMessage msgToReceiveMessage(String xml) {
        Document doc = XmlUtil.parseXml(xml);
        Element rootElement = XmlUtil.getRootElement(doc);
        ReceiveMessage receiveMessage = new ReceiveMessage();
        receiveMessage.setToUserName(XmlUtil.elementText(rootElement,"ToUserName"));
        receiveMessage.setFromUserName(XmlUtil.elementText(rootElement,"FromUserName"));
        receiveMessage.setCreateTime(XmlUtil.elementText(rootElement,"CreateTime"));
        receiveMessage.setMsgType(XmlUtil.elementText(rootElement,"MsgType"));
        receiveMessage.setContent(XmlUtil.elementText(rootElement,"Content"));
        receiveMessage.setMsgId(XmlUtil.elementText(rootElement,"MsgId"));
        receiveMessage.setEvent(XmlUtil.elementText(rootElement,"Event"));
        receiveMessage.setTicket(XmlUtil.elementText(rootElement,"Ticket"));
        return receiveMessage;
    }

    /**
     * 是否是订阅事件
     *
     * @param receiveMessage
     * @return
     */
    public static boolean isEventAndSubscribe(ReceiveMessage receiveMessage) {
        return StringUtils.equals(receiveMessage.getEvent(), EVENT_SUBSCRIBE);
    }

    /**
     * 是否是二维码扫描事件
     *
     * @param receiveMessage
     * @return
     */
    public static boolean isScanQrCode(ReceiveMessage receiveMessage) {
        return StringUtils.isNotEmpty(receiveMessage.getTicket());
    }

}